﻿Public Class MetaCommandExplorer
    Inherits ExplorerTreeList
    Implements IExplorer


    Public EditPanePL As PLBase

    Public Sub New(ByVal aQueryName As String)
        MyBase.New(aQueryName)
    End Sub

    Public Sub New()
        MyBase.New()
    End Sub

    Public Overrides Sub ActionOptionLoad()
        MyBase.ActionOptionLoad()
        MetaActionOptionListLoad()
    End Sub



    Public Sub MetaActionOptionListLoad() Implements IExplorer.MetaActionOptionListLoad
        MetaControlTreeListActionOptionList.Add(New ActionOption("MetaCommandXML", "ACT_00010", "Export Command", AddressOf TreeExportCommand, True, True))

    End Sub

#Region "DevExpress Sample code for Drag and Drop a row"


    Private Sub AfterProcessGridKey(ByVal sender As Object, ByVal e As KeyEventArgs)
        ''Fonctionne avec les query qui on un champ pOrder
        'If e.Control AndAlso e.KeyCode = Keys.Subtract Then

        '    MoveRowUp(CType(sender, GridControl))
        'End If

        'If e.Control AndAlso e.KeyCode = Keys.Add Then
        '    MoveRowDown(CType(sender, GridControl))
        'End If
    End Sub



    Private Sub MoveRowUp(ByVal gridcontrol As GridControl)
        Dim view As GridView = DirectCast(gridcontrol.FocusedView, GridView)

        view.GridControl.Focus()
        Dim index As Integer = view.FocusedRowHandle
        If index <= 0 Then
            Return
        End If

        Dim row1 As DataRow = view.GetDataRow(index)
        Dim row2 As DataRow = view.GetDataRow(index - 1)
        If row1.Table.Columns.Contains("pOrder") Then

            Dim val1 As Object = row1("pOrder")
            Dim val2 As Object = row2("pOrder")
            row1("pOrder") = val2
            row2("pOrder") = val1

            view.FocusedRowHandle = index - 1
        End If
    End Sub

    Private Sub MoveRowDown(ByVal gridcontrol As GridControl)
        Dim view As GridView = DirectCast(gridcontrol.FocusedView, GridView)
        view.GridControl.Focus()
        Dim index As Integer = view.FocusedRowHandle
        If index >= view.DataRowCount - 1 Then
            Return
        End If

        Dim row1 As DataRow = view.GetDataRow(index)
        Dim row2 As DataRow = view.GetDataRow(index + 1)

        If row1.Table.Columns.Contains("pOrder") Then
            Dim val1 As Object = row1("pOrder")
            Dim val2 As Object = row2("pOrder")
            row1("pOrder") = val2
            row2("pOrder") = val1
            view.FocusedRowHandle = index + 1
        End If
    End Sub




    Private downHitInfo As Grid.ViewInfo.GridHitInfo = Nothing
    Private Sub MouseDownExt(ByVal sender As Object, ByVal e As MouseEventArgs)
        Dim view As GridView = TryCast(sender, GridView)
        downHitInfo = Nothing

        Dim hitInfo As Grid.ViewInfo.GridHitInfo = view.CalcHitInfo(New Point(e.X, e.Y))
        If Control.ModifierKeys <> Keys.None Then
            Return
        End If
        If e.Button = MouseButtons.Left AndAlso hitInfo.InRow AndAlso hitInfo.RowHandle <> GridControl.NewItemRowHandle Then
            downHitInfo = hitInfo
        End If
    End Sub

    Private Sub MouseMoveExt(ByVal sender As Object, ByVal e As MouseEventArgs)
        Dim view As GridView = TryCast(sender, GridView)
        If e.Button = MouseButtons.Left AndAlso downHitInfo IsNot Nothing Then
            Dim dragSize As Size = SystemInformation.DragSize
            Dim dragRect As New Rectangle(New Point(downHitInfo.HitPoint.X - dragSize.Width \ 2, downHitInfo.HitPoint.Y - dragSize.Height \ 2), dragSize)

            If (Not dragRect.Contains(New Point(e.X, e.Y))) Then
                view.GridControl.DoDragDrop(downHitInfo, DragDropEffects.All)
                downHitInfo = Nothing
            End If
        End If
    End Sub

    Private Sub DragOverExt(ByVal sender As Object, ByVal e As DragEventArgs)
        If e.Data.GetDataPresent(GetType(Grid.ViewInfo.GridHitInfo)) Then
            Dim downHitInfo As Grid.ViewInfo.GridHitInfo = TryCast(e.Data.GetData(GetType(Grid.ViewInfo.GridHitInfo)), Grid.ViewInfo.GridHitInfo)
            If downHitInfo Is Nothing Then
                Return
            End If

            Dim grid As GridControl = TryCast(sender, GridControl)
            Dim view As GridView = TryCast(grid.FocusedView, GridView)
            Dim hitInfo As Grid.ViewInfo.GridHitInfo = view.CalcHitInfo(grid.PointToClient(New Point(e.X, e.Y)))
            If hitInfo.InRow AndAlso hitInfo.RowHandle <> downHitInfo.RowHandle AndAlso hitInfo.RowHandle <> GridControl.NewItemRowHandle Then
                e.Effect = DragDropEffects.Move
            Else
                e.Effect = DragDropEffects.None
            End If
        End If

    End Sub

    Private Sub DragDropExt(ByVal sender As Object, ByVal e As DragEventArgs)
        Dim grid As GridControl = TryCast(sender, GridControl)
        Dim view As GridView = TryCast(grid.FocusedView, GridView)
        Dim srcHitInfo As Grid.ViewInfo.GridHitInfo = TryCast(e.Data.GetData(GetType(Grid.ViewInfo.GridHitInfo)), Grid.ViewInfo.GridHitInfo)
        Dim hitInfo As Grid.ViewInfo.GridHitInfo = view.CalcHitInfo(grid.PointToClient(New Point(e.X, e.Y)))
        Dim sourceRow As Integer = srcHitInfo.RowHandle
        Dim targetRow As Integer = hitInfo.RowHandle
        MoveRow(sourceRow, targetRow, view)

    End Sub

    Private Sub MoveRow(ByVal sourceRow As Integer, ByVal targetRow As Integer, ByVal view As GridView)
        If sourceRow = targetRow OrElse sourceRow = targetRow + 1 Then
            Return
        End If

        Dim row1 As DataRow = view.GetDataRow(targetRow)
        Dim row2 As DataRow = view.GetDataRow(targetRow + 1)
        Dim dragRow As DataRow = view.GetDataRow(sourceRow)
        Dim val1 As Decimal = CDec(row1("pOrder"))
        If row2 Is Nothing Then
            dragRow("pOrder") = val1 + 1
        Else
            Dim val2 As Decimal = CDec(row2("pOrder"))
            dragRow("pOrder") = (val1 + val2) / 2
        End If


        'BUGBUG: Utiliser les CTRL_+ et CTRL_-

        'view.CloseEditor()
        'view.UpdateCurrentRow()

        'MetaCommand_PL.ReorderColumns(CType(view.DataSource, MetaDataTable))
    End Sub


#End Region



    Public Overrides Sub PopulateDetailSection() Implements IExplorer.PopulateDetailSection
        Me.Cursor = Cursors.WaitCursor
        '
        ' Memory management / Help the GC
        If aGridControl IsNot Nothing Then
            aGridControl.Dispose()
            aGridControl = Nothing
        End If

        Dim guidEnfant As Guid
        Dim aPLName As String

        Dim DescriptionLang As String = "_PRM"


        Dim aPaneMetaQueryName As String
        Dim Ametaquerie As MetaQuery
        Dim frmCaption As String = "Query List"        'DeskTopManager.GetMessage("CONNECT") to be implemented when metastring has code

        Try
            guidEnfant = DirectCast(NodeDataRow(Me.KeyFieldName), Guid)
            aPLName = DirectCast(NodeDataRow("PL"), String)

            aPaneMetaQueryName = DirectCast(NodeDataRow("MetaQuerie"), String)
            Ametaquerie = MetaQuery.GetMetaQueryByName(aPaneMetaQueryName)

            'c'est ici qu'on bind les info du noeud qui articule le Edit PANE
            EditPanePL = PLBase.CreateInstanceOf(aPLName, aPaneMetaQueryName)

            aGridControl = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = EditPanePL, .SecureGrid = False, .Name = Ametaquerie.Caption, .FormCtrlCD = Me.PanelName}
            If Not Guid.Empty.Equals(guidEnfant) Then
                EditPanePL.SQLWhere = String.Format("{0} = '{1}'", Ametaquerie.GUIDField, guidEnfant)
                If AppManager.ApplicationOption.DescriptionColumnIndex = 3 Then
                    DescriptionLang = "_ALT"
                End If

                If NodeDataRow.Table.Columns.Contains("CODE") AndAlso NodeDataRow.Table.Columns.Contains("Description" & DescriptionLang) Then
                    frmCaption = String.Format("{0} - {1}", NodeDataRow("CODE"), NodeDataRow("Description" & DescriptionLang))
                Else
                    frmCaption = "CODE, Description" & DescriptionLang
                End If


            End If


        Catch ex As Exception
            MessageWindow.ShowMessage(ex)

        End Try
        'Appelle Dynamique du Menu Action (ContextMenu)
        AddHandler aGridControl.InitGridActionOptionList, AddressOf Init_GridActionOptionList
        AddHandler aGridControl.DetailMouseDown, AddressOf MouseDownExt
        AddHandler aGridControl.DetailMouseMove, AddressOf MouseMoveExt

        AddHandler aGridControl.DragOverExt, AddressOf DragOverExt
        AddHandler aGridControl.DragDropExt, AddressOf DragDropExt

        AddHandler aGridControl.AfterProcessGridKey, AddressOf AfterProcessGridKey
        AddHandler aGridControl.InitNewMasterRow, AddressOf InitNewMasterRowMetaCommand

        '
        'On trouve la form pour effacer les controle dedans et ensuite remettre le bon.
        'Comme ca on change le Detail selon la ligne dans L'explorer
        For Each aFrm As XtraForm In Me.ParentForm.MdiChildren
            If aFrm.Name = PanelName Then
                aFrm.Controls.Clear()
                aFrm.Controls.Add(aGridControl)
                aFrm.Text = frmCaption
                aFrm.Show()
                aFrm.Focus()
            End If
            aFrm.Refresh()
        Next

        Me.Cursor = Cursors.Default
    End Sub


    ''' <summary>
    ''' Init_GridActionOptionList
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Sub Init_GridActionOptionList(sender As Object, e As EventArgs)
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommandMaster", "ACT_00009", "Export Command to " + AppManager.ExportToMasterDB, AddressOf MenuExportCommandToMaster, True, True))

        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommandXML", "ACT_00010", "Export Command", AddressOf MenuExportCommand, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommandXML", "ACT_00011", "Import Command", AddressOf MenuImportCommand, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommandXML1", "ACT_00202", "Import Layout ", AddressOf MenuImportLayout, True, True))


        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommand1", "ACT_00012", "Copy MetaCommand", AddressOf MenuCopyMetaCommand, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommand1", "ACT_00013", "Export XSD Command", AddressOf ExportXsdCommand, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommand2", "ACT_00014", "Generate Columns (Values)", AddressOf MenuGenerateColumn, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommand2", "ACT_00015", "Generate Columns (Parameters)", AddressOf MenuGenerateParameterColumn, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommand2", "ACT_00016", "Get Relation", AddressOf MenuGetRelationMetaCommand, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommand3", "ACT_00017", "Preview MetaCommand", AddressOf MenuPreviewCommand, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommand4", "ACT_00018", "Publish To MetaControl", AddressOf MenuPublishMetacommandToMetaControl, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommand4", "ACT_00019", "Publish To MetaUserColumn", AddressOf MenuPublishMetaUserColumn, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommand4", "ACT_00020", "Reorder Columns", AddressOf MenuReOrderColumns, True, True))

        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommandSQL", "ACT_00021", "Validate MetaCommand", AddressOf ACT_00021_MenuValidateCommand, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommandSQL", "ACT_00022", "Validate MetaColumn Not In Command", AddressOf MenuValidateMetaColumn, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommandSQL", "ACT_00023", "View SQL Statement", AddressOf MenuViewSQLStatement, True, True))
        aGridControl.GridActionOptionList.Add(New ActionOption("MetaCommandSQL", "ACT_00024", "SQL Window (Flatten)", AddressOf MenuSQLWindowCommand, True, True))
    End Sub

    ''' <summary>
    ''' MenuImportLayout
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks>This SystemBOX Function launch the import of a saved grid Layout on the metacolumns attribute</remarks>
    Private Sub MenuImportLayout(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)
        Dim aQueryName As String = aDataRow("QueryName").ToString
        'need to get the metaquery.
        'need to load so the view has columns  

        Dim voidPL As SystemBoxSDK.PL.Void_PL = New SystemBoxSDK.PL.Void_PL(aQueryName)


        Dim aEXTGrid As GridExtPL = New GridExtPL With {.Pl = voidPL}
        aEXTGrid.InitGridExt()


        ImportLayout(aEXTGrid.GridView1)


    End Sub


    ''' <summary>
    ''' ImportLayout
    ''' </summary>
    ''' <remarks>This SystemBOX function permit to import Layout XML File and apply to the MetaColumn attribute</remarks>
    Private Sub ImportLayout(ByVal aGridview As GridView)

        Try
            Dim atable As DataTable = EditPanePL.Dataset.Tables("MetaColumns")


            Dim saved As Boolean = True
            Using aFile As New System.Windows.Forms.OpenFileDialog
                aFile.FileName = "GridExtLayout_*"
                aFile.DefaultExt = "xml"
                aFile.Multiselect = False
                aFile.AutoUpgradeEnabled = True
                If aFile.ShowDialog() = DialogResult.OK Then
                    'Load Layout For the Focus View (from XML file on computer)

                    aGridview.RestoreLayoutFromXml(aFile.FileName)
                End If
                ' take the Guid of the metaquery filter the columns Table by that Guid.

                '
                For Each aColumn As GridColumn In aGridview.Columns
                    Console.WriteLine(aColumn.FieldName)
                    Dim arow() As DataRow = atable.Select("ColumnName = '" & aColumn.FieldName & "'")
                    If aColumn.VisibleIndex > -1 Then
                        arow(0)("pOrder") = aColumn.VisibleIndex
                    End If
                    If aColumn.Visible Then
                        arow(0)("pVisible") = 1
                    Else
                        arow(0)("pVisible") = 0
                    End If

                    arow(0)("pWidth") = aColumn.Width
                Next

                'loop the gridcolumns and maps coloumn properties to Metacolumnporp of rows of the Column of the metaquery

                EditPanePL.Save()
            End Using

            MessageWindow.ShowMessage("Import Layout Successful", MsgBoxStyle.Information)


        Catch ex As Exception
            MessageWindow.ShowMessage(ex)

        End Try



    End Sub



End Class
